package com.iflytek.autofly.setting.biz.networking;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.base.BottomMenu;
import com.iflytek.autofly.setting.biz.base.MyBaseAdapter;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.sunflower.FlowerCollector;

import java.util.ArrayList;

/**
 * <b>Description: </b>wlan界面可用设备列表的adapter<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>yutian2@iflytek.com</td>
 * <td>2015年5月26日</td>
 * <td>上午10:17:11</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author yutian2@iflytek.com
 */
public class WlanListAdapter extends MyBaseAdapter {
    private static final String TAG = "WlanListAdapter";
    private static final int LEVEL_COUNT = 4;
    private static final int[] STRENGTH_RES_ID = {
            R.drawable.net_wifi_unconnect_public_signal_1,
            R.drawable.net_wifi_unconnect_public_signal_2,
            R.drawable.net_wifi_unconnect_public_signal_3,
            R.drawable.net_wifi_unconnect_public_signal_4,
            R.drawable.net_wifi_connect_public_signal_1,
            R.drawable.net_wifi_connect_public_signal_2,
            R.drawable.net_wifi_connect_public_signal_3,
            R.drawable.net_wifi_connect_public_signal_4,
            R.drawable.net_wifi_unconnect_encrypted_signal_1,
            R.drawable.net_wifi_unconnect_encrypted_signal_2,
            R.drawable.net_wifi_unconnect_encrypted_signal_3,
            R.drawable.net_wifi_unconnect_encrypted_signal_4,
            R.drawable.net_wifi_connect_encrypted_signal_1,
            R.drawable.net_wifi_connect_encrypted_signal_2,
            R.drawable.net_wifi_connect_encrypted_signal_3,
            R.drawable.net_wifi_connect_encrypted_signal_4
    };

    private WlanSetting mWlanSetting;
    private Activity mActivity;
    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AccessPoint bean = (AccessPoint) v.getTag();
            switch (bean.getFlyState()) {
                case CONNECTING:
                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.net_wifi_action_connecting), "button_click");
                    mWlanSetting.cancelConnect(bean);
                    break;
                case CONNECTED:
                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.net_wifi_action_connected), "button_click");
                    mWlanSetting.disconnect(bean);
                    break;
                case VERIFY_FAILED:
                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.net_wifi_action_verify_failed), "button_click");
                    mWlanSetting.connect(bean);
                    break;
                case UNCONNECTED:
                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.net_wifi_action_unconnected), "button_click");
                    mWlanSetting.connect(bean);
                    break;
                case SAVED:
                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.net_wifi_action_saved), "button_click");
                    mWlanSetting.connect(bean);
                    break;
                default:
                    FlyLog.e(TAG, "unknown status[" + bean.getFlyState() + "]");
            }
        }
    };
    private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            final AccessPoint bean = (AccessPoint) v.getTag();

            if (bean.getFlyState() == AccessPoint.FlyState.CONNECTING) {
                return true;
            }

            final TextView stateTv = (TextView) v.findViewById(R.id.net_wifi_item_state);
            final Button actionBtn = (Button) v.findViewById(R.id.net_wifi_item_action_btn);
            final ImageView selectedIv = (ImageView) v.findViewById(R.id.net_wifi_item_selected_iv);

            stateTv.setVisibility(View.GONE);
            actionBtn.setVisibility(View.GONE);
            selectedIv.setVisibility(View.VISIBLE);

            PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    stateTv.setVisibility(View.VISIBLE);
                    actionBtn.setVisibility(View.VISIBLE);
                    selectedIv.setVisibility(View.GONE);
                }
            };

//            3，wifi已保存密码（未连接）：删除、修改密码；
//            4，wifi未保存密码：连接；
//            5，wifi已连接/正在连接：断开连接；
            switch (bean.getFlyState()) {
                case CONNECTING:
                    break;
                case CONNECTED:
                    new BottomMenu(mActivity, R.layout.menu_connected_wifi)
                            .setButtonListener(R.id.menu_disconnect_wifi, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.menu_disconnect_wifi), "long_click");
                                    mWlanSetting.disconnect(bean);
                                }
                            })
                            .setOnDismissListener(dismissListener)
                            .show();
                    break;
                case VERIFY_FAILED:
                case SAVED:
                    if (bean.getSecurity() != AccessPoint.SECURITY_NONE) {
                        new BottomMenu(mActivity, R.layout.menu_saved_wifi)
                                .setButtonListener(R.id.menu_modify_wifi, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.menu_modify_wifi), "long_click");
                                        mWlanSetting.modify(bean);
                                    }
                                })
                                .setButtonListener(R.id.menu_delete_wifi, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.menu_delete_wifi), "long_click");
                                        mWlanSetting.forget(bean);
                                    }
                                })
                                .setOnDismissListener(dismissListener)
                                .show();
                    } else {
                        new BottomMenu(mActivity, R.layout.menu_saved_public_wifi)
                                .setButtonListener(R.id.menu_delete_wifi, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.menu_delete_wifi), "long_click");
                                        mWlanSetting.forget(bean);
                                    }
                                })
                                .setOnDismissListener(dismissListener)
                                .show();
                    }
                    break;
                case UNCONNECTED:
                    new BottomMenu(mActivity, R.layout.menu_unconnected_wifi)
                            .setButtonListener(R.id.menu_connect_wifi, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    FlowerCollector.onEvent(mActivity.getApplicationContext(), mActivity.getString(R.string.networking) + "-" + mActivity.getString(R.string.net_wifi) + "-" + mActivity.getString(R.string.menu_connect_wifi), "long_click");
                                    mWlanSetting.connect(bean);
                                }
                            })
                            .setOnDismissListener(dismissListener)
                            .show();
                    break;
                default:
                    FlyLog.e(TAG, "unknown status[" + bean.getFlyState() + "]");
            }

            return true;
        }
    };

    public WlanListAdapter(final Activity activity) {
        super();
        // 初始化
        this.mContext = activity;
        mActivity = activity;
        mItems = new ArrayList();
    }

    @Override
    public int getCount() {
        int size = mItems.size();
        for (int i = 0; i < size; i++) {
            if (((AccessPoint) mItems.get(i)).getLevel() == -1) {
                return i;
            }
        }
        return size;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            LayoutInflater lf = LayoutInflater.from(mContext);
            view = lf.inflate(R.layout.net_wifi_wlan_list_item, null);
        } else {
            view = convertView;
        }

        AccessPoint accessPoint = (AccessPoint) mItems.get(position);
        view.setTag(accessPoint);

        ImageView strenghtIv = (ImageView) view.findViewById(R.id.icon);
        RelativeLayout itemRl = (RelativeLayout) view.findViewById(R.id.net_wifi_item_rl);
        TextView nameTv = (TextView) view.findViewById(R.id.name);
        TextView stateTv = (TextView) view.findViewById(R.id.net_wifi_item_state);
        Button actionBtn = (Button) view.findViewById(R.id.net_wifi_item_action_btn);
        ImageView selectedIv = (ImageView) view.findViewById(R.id.net_wifi_item_selected_iv);

        AccessPoint.FlyState state = accessPoint.getFlyState();
        strenghtIv.setImageResource(
                getSignalResId(accessPoint.getLevel(),
                        state == AccessPoint.FlyState.CONNECTED,
                        accessPoint.security != AccessPoint.SECURITY_NONE));
        String ssid = accessPoint.ssid;
        if (ssid.length() > 20) {
            ssid = ssid.substring(0, 17) + "...";
        }
        nameTv.setText(ssid);

        if (!accessPoint.isFlyChecked()) {
            stateTv.setVisibility(View.VISIBLE);
            actionBtn.setVisibility(View.VISIBLE);
            selectedIv.setVisibility(View.GONE);
            actionBtn.setTag(accessPoint);
            actionBtn.setOnClickListener(mOnClickListener);
            itemRl.setOnLongClickListener(mOnLongClickListener);
            itemRl.setTag(accessPoint);

            actionBtn.setTextColor(mContext.getResources().getColor(R.color.net_bt_device_action_btn_fontcolor));
            switch (state) {
                case CONNECTING:
                    actionBtn.setText(mContext.getString(R.string.net_wifi_action_connecting));
                    actionBtn.setBackgroundResource(R.drawable.net_bt_action_connecting);
                    stateTv.setText(mContext.getString(R.string.net_wifi_state_connecting));
                    actionBtn.setEnabled(false);
                    break;
                case CONNECTED:
                    actionBtn.setTextColor(mContext.getResources().getColor(R.color.net_bt_device_action_btn_fontcolor_connected));
                    actionBtn.setBackgroundResource(R.drawable.net_bt_action_connected);
                    actionBtn.setText(mContext.getString(R.string.net_wifi_action_connected));
                    stateTv.setText(mContext.getString(R.string.net_wifi_state_connected));
                    actionBtn.setEnabled(true);
                    break;
                case VERIFY_FAILED:
                    actionBtn.setBackgroundResource(R.drawable.net_bt_action_connect_failed);
                    actionBtn.setText(mContext.getString(R.string.net_wifi_action_verify_failed));
                    stateTv.setText(mContext.getString(R.string.net_wifi_state_verify_failed));
                    actionBtn.setEnabled(true);
                    break;
                case UNCONNECTED:
                    actionBtn.setBackgroundResource(R.drawable.net_bt_action_paired);
                    actionBtn.setText(mContext.getString(R.string.net_wifi_action_unconnected));
                    stateTv.setText(mContext.getString(R.string.net_wifi_state_unconnected));
                    actionBtn.setEnabled(true);
                    break;
                case SAVED:
                    actionBtn.setBackgroundResource(R.drawable.net_bt_action_paired);
                    actionBtn.setText(mContext.getString(R.string.net_wifi_action_saved));
                    stateTv.setText(mContext.getString(R.string.net_wifi_state_saved));
                    actionBtn.setEnabled(true);
                    break;
            }
        } else {
            stateTv.setVisibility(View.GONE);
            actionBtn.setVisibility(View.GONE);
            selectedIv.setVisibility(View.VISIBLE);
        }
        return view;
    }

    public void setWlanMngr(WlanSetting manager) {
        mWlanSetting = manager;
    }

    private int getSignalResId(int level, boolean isConnected, boolean isEncrypted) {
        if (level < 0 || level > LEVEL_COUNT) {
            return R.drawable.net_wifi_signal_0;
        }
        int index = level;
        if (isConnected) {
            index += LEVEL_COUNT;
        }
        if (isEncrypted) {
            index += LEVEL_COUNT * 2;
        }

        return STRENGTH_RES_ID[index];
    }
}
